import axios from 'axios'
import Vue from 'vue'
import router from '../router'
let vue = new Vue({
  router
})

export default function request(config) {
  // 1.创建axios的实例
  const instance = axios.create({
    baseURL: '/api',
    timeout: 8000,
  })

  // 2.axios的拦截器
  // 2.1.请求拦截的作用
  instance.interceptors.request.use(config => {
    var token = window.localStorage.getItem('token');
    if (token) {
      config.headers['Authorization'] = 'Bearer ' + token;
    }
    return config
  }, err => {
    console.log(err);
  })

  // 2.2.响应拦截
  instance.interceptors.response.use(res => {
    // console.log(res.data.code);
    if(res.data.code == 401) {
      // window.location.href = "/#/login"
      vue.$router.push('/login')
    }
    return res.data
  }, err => {
    console.log(err);
  })

  // 3.发送真正的网络请求
  return instance(config)
}

export function $upload(Url, data, handle) {
  let instance = axios.create({
    baseURL: '',
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  });
  instance.post(Url, data).then(res => {
    handle(res.data);
  }).catch(error => {
    // console.log(error);
    this.$toast({
      message: "服务器错误",
      position: "bottom"
    })
  })
};